<template>
  <div class="container" v-if="showIndex">
    <div class="warp">
      <div class="statisticsCount clearfix">
        <div class="left leftBox">
          <div class="headContentWarp">
            <span class="title">本月目标</span>
            <span class="number">{{getMonthPlan()}}</span>
          </div>
          <div class="headContentWarp">
            <span class="title">完成量</span>
            <span class="number">{{programOutput()}}</span>
          </div>
        </div>
        <div class="right rightBox">
          <div class="headContentWarp">
            <span class="title">完成单数</span>
            <span class="number">{{programSingular()}}</span>
          </div>
          <div class="headContentWarp">
            <span class="title">完成比</span>
            <span class="number">{{getprogramOutput()}}</span>
          </div>
        </div>
      </div>
      <div class="interest">
        <p>
          <span>昨日留言量</span>
          <span>{{getTodayMsg()}}</span>
        </p>
        <p>
          <span>单条成本</span>
          <span>{{singleCost()}}</span>
        </p>
        <p>
          <span>客户转换率</span>
          <span>{{conversionRate()}}</span>
        </p>
      </div>
      <div class="tableWarp">
        <div class="tableTitle">
          <span>月度绩效汇总</span>
          <div>
            <span
              @click="changeMonthlyPerformance(true)"
              :class="[monthlyPerformance ? 'currentMonth monthClass' : 'monthClass']"
            >上月</span>
            <span
              @click="changeMonthlyPerformance(false)"
              :class="[!monthlyPerformance ? 'currentMonth monthClass' : 'monthClass']"
            >本月</span>
          </div>
        </div>
        <table class="table1 specialTable" border="1" frame="void" rules="none" width="100%">
          <thead>
            <tr>
              <th>部门</th>
              <th>项目</th>
              <th>签约总额(元)</th>
              <th>单数合计</th>
              <th>全款服务费(元)</th>
              <th>全款完成率</th>
            </tr>
          </thead>
          <tbody>
            <tr
              v-for="(item,index) in performanceList"
              :style="{'border-bottom':showShowSpan(item,index) ? '1px solid #e8e8e8' :''}"
              :key="index"
            >
              <td
                v-show="getShowSpan(item,index)"
                :rowspan="getRowSpan(item)"
                :style="{'border':`1px solid #e8e8e8`}"
              >{{item.tdparentname}}</td>
              <td>{{item.tdname}}</td>
              <td>{{toMoney(item.contactpayment)}}</td>
              <td>{{item.contactnumber}}</td>
              <td>{{toMoney(item.fullservice)}}</td>
              <td>{{Number(item.fulfilrate).toFixed(2) + '%'}}</td>
            </tr>
          </tbody>
        </table>
      </div>
       <div class="tableWarp">
        <div class="tableTitle">
          <p>平台效果分析</p>
          <p>时间区间：{{dateArrayZzz[0].date,}}至{{dateArrayZzz[dateArrayZzz.length - 1].date}}</p>
        </div>
        <table class="table1 specialTable" border="1" frame="void" rules="none" width="100%">
          <thead>
            <tr>
              <th>序号</th>
              <th>项目名称</th>
              <th>留言量</th>
              <th>单条成本</th>
              <th>灌水率</th>
              <th>重点转换率</th>
            </tr>
          </thead>
          <tbody v-if="platformAssessment.length">
            <tr v-for="(item,index) in platformAssessment" :key="index">
              <td>{{++index}}</td>
              <td>{{item.projectname}}</td>
              <td>{{item.trmdcount}}</td>
              <td>{{(item.assignamount.replace(new RegExp(/,/g), "") / item.trmdcount).toFixed(2)}}</td>
              <td>{{Number(item.trmfdcount) ==0 || Number(item.trmdcount)==0 ? "0%" :((item.trmfdcount / item.trmdcount)* 100 ).toFixed(2)+ '%'}}</td>
              <td>{{Number(item.amount) ==0 || Number(item.trmdcount)==0 ? "0%" :((item.amount / item.trmdcount) * 100).toFixed(2) + '%'}}</td>
            </tr>
          </tbody>
          <tbody v-else>
            <tr>
              <td colspan="6" style="text-align:center;">没有找到您想要的数据</td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="tableWarp">
        <div class="tableTitle">
          <p>人员转换排名</p>
          <p>时间区间：{{dateArrayZzz[0].date,}}至{{dateArrayZzz[dateArrayZzz.length - 1].date}}</p>
        </div>
        <table class="table1 specialTable" border="1" frame="void" rules="none" width="100%">
          <thead>
            <tr>
              <th>序号</th>
              <th>部门</th>
              <th>分配数</th>
              <th>转换数</th>
              <th>重点转换率</th>
            </tr>
          </thead>
          <tbody v-if="conversionRanking.length">
            <tr v-for="(item,index) in conversionRanking" :key="index">
              <td>{{++index}}</td>
              <td>{{item.depname}}</td>
              <td>{{item.assign}}</td>
              <td>{{item.nums}}</td>
              <td>{{getConversionRankingInterest(item)}}</td>
            </tr>
          </tbody>
          <tbody v-else>
            <tr>
              <td colspan="6" style="text-align:center;">没有找到您想要的数据</td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="tableWarp">
        <div class="tableTitle">
          <span>业绩进展分析</span>
          <div>
            <span
              @click="changeProgressPerformance(true)"
              :class="[progressPerformance ? 'currentMonth monthClass' : 'monthClass']"
            >上月</span>
            <span
              @click="changeProgressPerformance(false)"
              :class="[!progressPerformance ? 'currentMonth monthClass' : 'monthClass']"
            >本月</span>
          </div>
        </div>
        <table class="table1" border="1" frame="void" rules="none" width="100%">
          <thead>
            <tr>
              <th>序号</th>
              <th>项目名称</th>
              <th>目标</th>
              <th>完成量</th>
              <th>完成单数</th>
              <th>已完成</th>
            </tr>
          </thead>
          <tbody v-if="MonthSingular1.length">
            <tr v-for="(item,index) in MonthSingular1" :key="index">
              <td>{{++index}}</td>
              <td>{{item.tdname}}</td>
              <td>{{toMoney(item.target)}}</td>
              <td>{{toMoney(item.samount)}}</td>
              <td>{{item.singular}}</td>
              <td>{{getSingular(item)}}</td>
            </tr>
          </tbody>
          <tbody v-else>
            <tr>
              <td colspan="6" style="text-align:center;">没有找到您想要的数据</td>
            </tr>
          </tbody>
        </table>
      </div>
      <canvas id="myChart" :width="winInnerWid" height="260"></canvas>
      <div style="height:60px;"></div>
    </div>
  </div>
  <div
    v-else
    class="jianquan"
    :style="{'height':winInnerHei + 'px'}"
  >{{notInDingTalkEnv ? '请使用钉钉打开应用' :'正在鉴别请稍后'}}</div>
</template>

<script>
import axios from "axios";
import F2 from "@antv/f2";
import qs from "qs";
import _ from "lodash";
import * as dd from "dingtalk-jsapi";
let myDate = new Date(); //获取今天日期
let result = () => {
  return new Promise((resolve, reject) => {
    dd.ready(function() {
      dd.runtime.permission.requestAuthCode({
        corpId: "ding8bcc8f2eff21d46a", // 企业id
        onSuccess: function(info) {
          resolve(info);
        },
        onFail: function(err) {
          reject(err);
        }
      });
    });
  });
};
export default {
  data() {
    return {
      performanceList: [],
      MonthSingular: [],
      MonthSingular1: [],
      dateArrayZzz: [],
      lenArr: [],
      conversionRanking: [],
      platformAssessment: [],
      winInnerWid: 0,
      showIndex: false,
      winInnerHei: 0,
      notInDingTalkEnv: true,
      monthlyPerformance: false,
      progressPerformance: false
    };
  },
  created() {
    this.winInnerHei = window.innerHeight;
    myDate.setDate(myDate.getDate() - 7);
    let dateTemp; // 临时日期数据
    let flag = 1;
    for (let i = 0; i < 7; i++) {
      dateTemp =
        myDate.getFullYear() +
        "-" +
        (myDate.getMonth() + 1) +
        "-" +
        (myDate.getDate() <= 9 ? "0" + myDate.getDate() : myDate.getDate());
      this.dateArrayZzz.push({
        date: dateTemp
      });
      myDate.setDate(myDate.getDate() + flag);
    }
    if (dd.env.platform !== "notInDingTalk") {
      this.notInDingTalkEnv = true;
      return false;
    } else {
      this.notInDingTalkEnv = false;
    }
    // result()
    // .then(res => {
    //   axios
    //     .post(
    //       `/api/dingSignIn`,
    //       qs.stringify({
    //         code: res.code
    //       })
    //     )
    //     .then(res => {
    //       if (res.data.code == 100) {
    //         axios.defaults.withCredentials = true;
    //         this.getTableDataOne();
    //         this.changeProgressPerformance(false);
    //         this.changeMonthlyPerformance(false);
    //         this.showIndex = true;
    //       } else {
    //         alert(`登录错误，code：${res.data.code}`);
    //         this.showIndex = false;
    //       }
    //     });
    // })
    // .catch(err => {
    //   alert(JSON.stringify(err));
    // });
    document.cookie =
      "uid=Mg0HCQprMSI3x1AJYJ2QDE4GP06f-FySh1ilJxLfKVy80Yv9wxRt1WdKYP9jhNAEcOMGr8Znyo59qqDW14TMwsIT3izk6Jq5B2YYyTXuKauzEg8vxr0Gdx8nNyfRdPBK2GrPe2_6qc-toO9sy2J4wdPNX_aKFpJDQ-SCZho2Br8t8Y9OYI_Q_TEPr3Un";
    axios.defaults.withCredentials = true;
    this.getTableDataOne();
    this.changeProgressPerformance(false);
    this.changeMonthlyPerformance(false);
    this.getConversionRanking();
    this.showIndex = true;
    this.winInnerWid = window.innerWidth;
  },
  methods: {
    getConversionRankingInterest(item) {
      if (Number(item.nums) == 0 || Number(item.assign) == 0) {
        return "0%";
      } else {
        return ((Number(item.nums) / Number(item.assign)) * 100).toFixed(2) + "%";
      }
    },
    toMoney(num) {
      num = num.toFixed(2);
      num = parseFloat(num);
      num = num.toLocaleString();
      return num; //返回的是字符串23,245.12保留2位小数
    },
    getprogramOutput() {
      let target = 0;
      let samount = 0;
      this.MonthSingular.length
        ? this.MonthSingular.map(v => (target += v.target))
        : "";
      this.MonthSingular.length
        ? this.MonthSingular.map(v => (samount += v.samount))
        : "";
      return samount && target
        ? ((samount / target) * 100).toFixed(2) + "%"
        : 0;
    },
    programSingular() {
      let singular = 0;
      this.MonthSingular.length
        ? this.MonthSingular.map(v => (singular += v.singular))
        : "";
      return singular;
    },
    programOutput() {
      let samount = 0;
      this.MonthSingular.length
        ? this.MonthSingular.map(v => (samount += v.samount))
        : "";
      return samount;
    },
    getMonthPlan() {
      let result = 0;
      this.MonthSingular.length
        ? this.MonthSingular.map(v => (result += v.target))
        : "";
      return result;
    },
    conversionRate() {
      let amount = 0;
      let trmdcount = 0;
      this.platformAssessment.map(v => {
        trmdcount += Number(v.trmdcount);
        amount += Number(v.amount);
      });
      return amount && trmdcount
        ? ((amount / trmdcount) * 100).toFixed(2) + "%"
        : 0;
    },
    singleCost() {
      let trmfdcount = 0;
      let trmdcount = 0;
      this.platformAssessment.map(v => {
        trmdcount += Number(v.trmdcount);
        trmfdcount += Number(v.assignamount.replace(new RegExp(/,/g), ""));
      });
      return trmfdcount && trmdcount ? (trmfdcount / trmdcount).toFixed(2) : 0;
    },
    getTodayMsg() {
      let result = 0;
      this.platformAssessment.map(v => (result += v.trmdcount));
      return result;
    },
    showShowSpan(res, index) {
      ++index;
      return this.lenArr.some(v => v.index == index);
    },
    getShowSpan(res, index) {
      return this.lenArr.some(v => v.index == index);
    },
    getRowSpan(res) {
      return this.lenArr.some(v => v.name == res.tdparentname)
        ? this.lenArr.filter(v => v.name == res.tdparentname)[0].len
        : "";
    },
    getConversionRanking() {
      axios
        .post(
          "/api/homePage/getConversionRanking",
          qs.stringify({
            groupId: "",
            queryTime:this.dateArrayZzz[this.dateArrayZzz.length - 1].date,
            qdep: true
          }),
          { headers: { "Content-Type": "application/x-www-form-urlencoded" } }
        )
        .then(res => {
          if (res.data.code == 100) {
            this.conversionRanking = res.data.data;
          } else {
            this.$message.error(err);
          }
        });
    },
    getTableDataOne() {
      axios
        .post(
          "/api/homePage/getPlatformAssessment",
          qs.stringify({
            projectId: "",
            startTime: this.dateArrayZzz[0].date,
            endTime: this.dateArrayZzz[this.dateArrayZzz.length - 1].date
          }),
          { headers: { "Content-Type": "application/x-www-form-urlencoded" } }
        )
        .then(res => {
          if (res.data.code == 100) {
            this.platformAssessment = res.data.data;
          } else {
            this.$message.error(err);
          }
        });
    },
    changeProgressPerformance(res) {
      this.progressPerformance = res;
      axios
        .post(
          "/api/homePage/getMonthSingular",
          qs.stringify({
            yearOrMonth: this.getPerformanceList(res)
          }),
          { headers: { "Content-Type": "application/x-www-form-urlencoded" } }
        )
        .then(res => {
          if (res.data.code == 100 && res.data.data) {
            this.MonthSingular = this.progressPerformance
              ? ""
              : JSON.parse(JSON.stringify(res.data.data));
            this.MonthSingular1 = JSON.parse(JSON.stringify(res.data.data));
            let dataArr = res.data.data.map(v => v.tdname);
            let samount = res.data.data.map(v => v.samount);
            let target = res.data.data.map(v => v.target);
            this.renderF2(dataArr, samount, target);
          } else if (res.data.code == 100) {
            this.MonthSingular1 = [];
          } else {
            this.$message.error(err);
          }
        });
    },
    renderF2(dataArr, samount, target) {
      const data = [];
      dataArr.map((v, index) => {
        data.push({
          name: "完成量",
          完成量: v,
          目标: samount[index]
        });
        data.push({
          name: "目标",
          完成量: v,
          目标: target[index]
        });
      });
      const chart = new F2.Chart({
        id: "myChart",
        pixelRatio: window.devicePixelRatio // 指定分辨率
      });
      chart.source(data);
      chart.axis("完成量", {
        label: {
          rotate: -Math.PI / 4,
          textAlign: "end",
          textBaseline: "middle"
        }
      });
      chart.tooltip({
        custom: true, // 自定义 tooltip 内容框
        onChange: function onChange(obj) {
          const legend = chart.get("legendController").legends.top[0];
          const tooltipItems = obj.items;
          const legendItems = legend.items;
          const map = {};
          legendItems.forEach(function(item) {
            map[item.name] = _.clone(item);
          });
          tooltipItems.forEach(function(item) {
            const name = item.name;
            const value = item.value;
            if (map[name]) {
              map[name].value = value;
            }
          });
          legend.setItems(_.values(map));
        },
        onHide: function onHide() {
          const legend = chart.get("legendController").legends.top[0];
          legend.setItems(chart.getLegendItems().country);
        }
      });
      chart
        .interval()
        .position("完成量*目标")
        .color("name")
        .adjust({
          type: "dodge",
          marginRatio: 0.05 // 设置分组间柱子的间距
        });
      chart.render();
    },
    changeMonthlyPerformance(res) {
      this.monthlyPerformance = res;
      axios
        .post(
          "/api/performance/list",
          qs.stringify({
            month: this.getPerformanceList(res)
          }),
          { headers: { "Content-Type": "application/x-www-form-urlencoded" } }
        )
        .then(res => {
          if (res.data.code == 100) {
            let tdparentnameArr = [
              ...new Set(res.data.data.map(v => v.tdparentname))
            ];
            let resultArr = [];
            let tpIndexArr = [];
            tdparentnameArr.map((v, z) => {
              resultArr[z] = {
                contactpayment: 0,
                confirmedamount: 0,
                contactnumber: 0,
                fulfilrate: 0,
                fullnumber: 0,
                fullpayment: 0,
                fullrate: 0,
                fullservice: 0,
                fullsingular: 0,
                target: 0,
                tdparentname: ""
              };
              resultArr[z].tdparentname = v;
              res.data.data.map((vv, index) => {
                if (vv.tdparentname == v) {
                  tpIndexArr[z] = ++index + z;
                  resultArr[z].contactpayment += Number(vv.contactpayment);
                  resultArr[z].confirmedamount += Number(vv.confirmedamount);
                  resultArr[z].contactnumber += Number(vv.contactnumber);
                  resultArr[z].fulfilrate += Number(vv.fulfilrate);
                  resultArr[z].fullnumber += Number(vv.fullnumber);
                  resultArr[z].fullpayment += Number(vv.fullpayment);
                  resultArr[z].fullservice += Number(vv.fullservice);
                  resultArr[z].fullsingular += Number(vv.fullsingular);
                  resultArr[z].target += Number(vv.target);
                  resultArr[z].tdname = "合计";
                  resultArr[z].tdparentname = v;
                  resultArr[z].fullrate =
                    resultArr[z].fullnumber && resultArr[z].contactnumber
                      ? (
                          (Number(resultArr[z].fullnumber) /
                            Number(resultArr[z].contactnumber)) *
                          100
                        ).toFixed(2)
                      : "";
                  resultArr[z].fulfilrate =
                    resultArr[z].fullservice && resultArr[z].target
                      ? (
                          (Number(resultArr[z].fullservice) /
                            Number(resultArr[z].target)) *
                          100
                        ).toFixed(2)
                      : "";
                }
              });
            });
            tpIndexArr.map((v, index) => {
              res.data.data.splice(v, 0, resultArr[index]);
            });
            let newEmptyObj = {
              confirmedamount: "",
              contactnumber: "",
              contactpayment: "",
              fulfilrate: "",
              fullnumber: "",
              fullpayment: "",
              fullrate: "",
              fullservice: "",
              fullsingular: "",
              target: "",
              tdname: "",
              tdparentname: "合计",
              tpname: ""
            };
            res.data.data.forEach(function(v) {
              newEmptyObj.confirmedamount =
                Number(newEmptyObj.confirmedamount) + Number(v.confirmedamount);
              newEmptyObj.contactnumber =
                Number(newEmptyObj.contactnumber) + Number(v.contactnumber);
              newEmptyObj.contactpayment =
                Number(newEmptyObj.contactpayment) + Number(v.contactpayment);
              newEmptyObj.fullnumber =
                Number(newEmptyObj.fullnumber) + Number(v.fullnumber);
              newEmptyObj.fullpayment =
                Number(newEmptyObj.fullpayment) + Number(v.fullpayment);
              newEmptyObj.fullservice =
                Number(newEmptyObj.fullservice) + Number(v.fullservice);
              newEmptyObj.fullsingular =
                Number(newEmptyObj.fullsingular) + Number(v.fullsingular);
              newEmptyObj.target =
                Number(newEmptyObj.target) + Number(v.target);
            });
            newEmptyObj.fullrate =
              newEmptyObj.fullnumber && newEmptyObj.contactnumber
                ? (
                    (Number(newEmptyObj.fullnumber) /
                      Number(newEmptyObj.contactnumber)) *
                    100
                  ).toFixed(2)
                : "";
            newEmptyObj.fulfilrate =
              newEmptyObj.fullservice && newEmptyObj.target
                ? (
                    (Number(newEmptyObj.fullservice) /
                      Number(newEmptyObj.target)) *
                    100
                  ).toFixed(2)
                : "";
            res.data.data.push(newEmptyObj);
            this.performanceList = res.data.data;
            let lenArr = [];
            let data = [...new Set(res.data.data.map(v => v.tdparentname))];
            data.map(v => {
              lenArr.push({ name: v, len: 0 });
            });
            lenArr.map((v, index) => {
              res.data.data.map((vv, z) => {
                if (vv.tdparentname == v.name) {
                  v.len += 1;
                  v.index != undefined ? v.index : (v.index = z);
                }
              });
            });
            this.lenArr = lenArr;
          } else {
            this.$message.error(err);
          }
        });
    },
    getPerformanceList(res) {
      if (res) {
        if (myDate.getMonth() == 0) {
          return myDate.getFullYear() - 1 + "-12";
        } else {
          return myDate.getFullYear() + "-" + this.zeroFill(myDate.getMonth());
        }
      } else {
        return (
          myDate.getFullYear() + "-" + this.zeroFill(myDate.getMonth() + 1)
        );
      }
    },
    getSingular(res) {
      if (Number(res.samount) == 0 || Number(res.target) == 0) {
        return "0%";
      }
      return (
        ((Number(res.samount) / Number(res.target)) * 100).toFixed(2) + "%"
      );
    },
    zeroFill(i) {
      if (i >= 0 && i <= 9) {
        return "0" + i;
      } else {
        return i;
      }
    }
  }
};
</script>

<style lang='scss'>
.monthClass {
  padding: 10px 30px;
  background: #909399;
  color: #fff;
}
.currentMonth {
  background: #f56c6c;
}
.jianquan {
  font-size: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
}
* {
  margin: 0;
  padding: 0;
}
.left {
  float: left;
}
.right {
  float: right;
}
.clearfix:after {
  visibility: hidden;
  display: block;
  font-size: 0;
  content: " ";
  clear: both;
  height: 0;
}
body,
html {
  font-size: 100px; /*no */
}
.warp {
  padding: 16px 18px 0 18px;
  width: 100%;
  background: #f6f6fa;
}
.statisticsCount {
  .title {
    font-size: 22px;
    color: #fff;
  }
  .number {
    font-size: 24px;
    color: #fff;
  }
  .leftBox {
    background: #5691ee;
    width: calc(50% - 10px);
    padding: 20px 0 24px 0;
    border-radius: 20px;
  }
  .rightBox {
    background: #f1b46a;
    border-radius: 12px;
    padding: 20px 0 24px 0;
    width: calc(50% - 10px);
  }
  .headContentWarp {
    display: flex;
  }
  .headContentWarp span {
    width: calc(50% - 22px);
    line-height: 62px;
    font-size: 36px;
  }
  .headContentWarp span:first-of-type {
    margin-right: 26px;
    text-align: right;
    font-size: 30px;
  }
  .headContentWarp span:last-of-type {
    font-weight: 700;
  }
}
.interest {
  margin-top: 20px;
  background: #fff;
  border-radius: 12px;
  height: 84px;
  line-height: 84px;
  display: flex;
  justify-content: space-around;
  p {
    display: flex;
    justify-content: flex-start;
  }
  p > span:first-of-type {
    font-size: 30px;
    color: #8390a4;
  }
  p > span:last-of-type {
    margin-left: 10px;
    font-size: 36px;
    color: #5691ee;
    font-weight: 700;
  }
}
.tableWarp {
  margin-top: 20px;
  background: #fff;
  padding-top: 20px;
  .tableTitle {
    display: flex;
    color: #4b565b;
    font-size: 36px;
    line-height: 60px;
    margin-bottom: 6px;
    text-indent: 18px;
    justify-content: space-between;
  }
}
.specialTable {
  tbody {
    tr:first-of-type {
      td:first-of-type {
        border-right: 1px solid #e8e8e8;
      }
    }
  }
}
.table1 {
  font-weight: 400 !important;
  text-align: center;
  thead th {
    font-size: 28px;
    line-height: 62px;
    font-weight: 400 !important;
    color: #6097ef;
  }
  thead tr {
    border-bottom: 6px solid #6097ef; /*no*/
  }
  tbody {
    color: #a3a3a3;
    font-size: 26px;
    font-weight: 700;
    tr {
      line-height: 64px;
    }
    tr:nth-of-type(odd) {
      background: #f5fafe;
    }
    tr:nth-of-type(even) {
      background: #fff;
    }
  }
}
</style>
